package com.yheriatovych.reductor.example.reductor.utils;

import com.yheriatovych.reductor.Action;
import com.yheriatovych.reductor.Reducer;

/**
 * Reducer which wrap other {@link Reducer} and add one action:
 * "SET_GLOBAL_STATE" to be able to replace state with provided value
 *
 * @param <T>
 * @since 2021-05-06
 */
public class SetStateReducer<T> implements Reducer<T> {
    /**
     * 类型常量
     */
    public static final String SET_GLOBAL_STATE = "SET_GLOBAL_STATE";
    private final Reducer<T> source;

    /**
     * 构造方法
     *
     * @param source
     */
    public SetStateReducer(Reducer<T> source) {
        this.source = source;
    }

    /**
     * 设置 state action
     *
     * @param value
     * @param <T>
     * @return Action
     */
    public static <T> Action setStateAction(T value) {
        return Action.create(SET_GLOBAL_STATE, value);
    }

    @Override
    public T reduce(T state, Action action) {
        if (action.type.equals(SET_GLOBAL_STATE)) {
            return (T) action.values;
        }
        return source.reduce(state, action);
    }
}
